import { defineConfig, loadEnv } from 'vite'
import path from 'path'
import createVitePlugins from './vite/plugins'
import tailwindcss from 'tailwindcss'

const timestamp = new Date().getTime()

// https://vite.dev/config/
export default defineConfig(({ mode, command }) => {
  const env = loadEnv(mode, './env', 'VITE_')
  const { VITE_APP_ENV, VITE_APP_BASE_API, VITE_APP_BASE_URL } = env
  console.log(VITE_APP_ENV, VITE_APP_BASE_API, VITE_APP_BASE_URL);
  return {
    envDir: './env',
    base: VITE_APP_ENV === 'production' ? './' : './',
    plugins: createVitePlugins(env, command === 'build'),
    resolve: {
      // https://cn.vitejs.dev/config/#resolve-alias
      alias: {
        // 设置路径
        '~': path.resolve(__dirname, './'),
        // 设置别名
        '@': path.resolve(__dirname, './src')
      },
      // https://cn.vitejs.dev/config/#resolve-extensions
      extensions: ['.mjs', '.js', '.ts', '.jsx', '.tsx', '.json', '.vue']
    },
    // vite 相关配置
    server: {
      port: 81,
      host: true,
      open: true,
      proxy: {
        [VITE_APP_BASE_API]: {
          target: VITE_APP_BASE_URL,
          changeOrigin: true,
          rewrite: path => path.replace('^' + VITE_APP_BASE_API, '')
        }
      },
      disableHostCheck: true
    },
    //fix:error:stdin>:7356:1: warning: "@charset" must be the first rule in the file
    css: {
      preprocessorOptions: {
        scss: {
          additionalData: `@use "@/assets/styles/theme-variables.scss" as *;`,
          javascriptEnabled: true,
          charset: false
        }
      },
      postcss: {
        plugins: [
          {
            postcssPlugin: 'internal:charset-removal',
            AtRule: {
              charset: (atRule) => {
                if (atRule.name === 'charset') {
                  atRule.remove();
                }
              }
            }
          },
          tailwindcss
        ]
      }
    },
    build: {
      cssCodeSplit: true,
      emptyOutDir: true,
      rollupOptions: {
        output: {
          // 最小化拆分包
          manualChunks: id => {
            if (id.includes('node_modules')) {
              return id.toString().split('node_modules/')[1].split('/')[0].toString()
            }
          },
          // 用于从入口点创建的块的打包输出格式[name]表示文件名,[hash]表示该文件内容hash值
          entryFileNames: `assets/js/[name].[hash].${timestamp}.js`,
          // 用于命名代码拆分时创建的共享块的输出命名
          chunkFileNames: `assets/js/[name].[hash].${timestamp}.js`,
          // 用于输出静态资源的命名，[ext]表示文件扩展名 `assets/[ext]/[name].[ext]`
          assetFileNames: (assetInfo) => {
            if (/\.(png|jpg|jpeg|gif|svg|webp|ico)$/.test(assetInfo.name)) {
              return "assets/images/[name].[ext]";
            }
            return "assets/[ext]/[name].[ext]";
          }
        }
      },
      terserOptions: {
        minify: "terser",
        compress: {
          drop_console: true, // 打包去除console
          drop_debugger: true, // 打包去除 debugger
          pure_funcs: ['console.log'] // 移除console
        }
      },
      reportCompressedSize: false, // 关闭文件计算
      sourcemap: false // 关闭生成map文件 可以达到缩小打包体积 这个生产环境一定要关闭，不然打包的产物会很大
    },
  }
})
